package cn.tedu.qxhouserent.house.service.impl;

import cn.tedu.qxhouserent.commons.web.ServiceCode;
import cn.tedu.qxhouserent.commons.ex.ServiceException;
import cn.tedu.qxhouserent.house.mapper.AgentMapper;
import cn.tedu.qxhouserent.house.mapper.HouseMapper;
import cn.tedu.qxhouserent.house.pojo.entity.Agent;
import cn.tedu.qxhouserent.house.pojo.entity.House;
import cn.tedu.qxhouserent.house.pojo.param.AgentAddNewParam;
import cn.tedu.qxhouserent.house.pojo.param.AgentUpdateInfoParam;
import cn.tedu.qxhouserent.house.pojo.vo.AgentListItemVO;
import cn.tedu.qxhouserent.house.pojo.vo.AgentStandardVO;
import cn.tedu.qxhouserent.commons.pojo.vo.PageData;
import cn.tedu.qxhouserent.house.service.AgentService;
import cn.tedu.qxhouserent.commons.util.PageInfoToPageDataConverter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static cn.tedu.qxhouserent.commons.web.ServiceCode.ERR_CONFLICT;

@Slf4j
@Service
public class AgentServiceImpl implements AgentService {

    @Autowired
    AgentMapper agentMapper;
    @Autowired
    HouseMapper houseMapper;

    @Override
    public void addNew(AgentAddNewParam agentAddNewParam) {
        log.debug("开始处理【添加经纪人】的业务，参数：{}", agentAddNewParam);
        // 检查经纪人身份证号是否被占用,如果被占用,则抛出异常
        QueryWrapper<Agent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card",agentAddNewParam.getIdCard());
        Integer countByIdCard = agentMapper.selectCount(queryWrapper);
        log.debug("根据身份证号统计匹配的经纪人数量，结果：{}", countByIdCard);
        if (countByIdCard > 0){
            String message = "添加经纪人失败,身份证号已经被占用!";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT,message);
        }

        // 检查经纪人电话号是否被占用,如果被占用,则抛出异常
        QueryWrapper<Agent> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("phone_number",agentAddNewParam.getPhoneNumber());
        Integer countByIdCard2 = agentMapper.selectCount(queryWrapper2);
        log.debug("根据电话号码统计匹配的经纪人数量，结果：{}", countByIdCard2);
        if (countByIdCard2 > 0){
            String message = "添加经纪人失败,电话号码已经被占用!";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT,message);
        }

        Agent agent = new Agent();
        BeanUtils.copyProperties(agentAddNewParam,agent);
        agent.setGmtCreate(LocalDateTime.now());
        agent.setGmtModified(LocalDateTime.now());
        log.debug("准备将新的经纪人数据写入到数据库，数据：{}", agent);
        int insert = agentMapper.insert(agent);
        if (insert != 1) {
            String message = "添加失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的经纪人数据写入到数据库，完成！");
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【根据ID删除经纪人】的业务，参数：{}", id);
        // 检查该管理员是否存在，如果不存在，则抛出异常
        QueryWrapper<Agent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = agentMapper.selectCount(queryWrapper);
        log.debug("根据经纪人ID统计匹配的经纪人数量，结果：{}", countById);
        if (countById == 0) {
            String message = "删除经纪人失败，该数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查是否有house关联到了此经纪人，如果存在，则抛出异常
        QueryWrapper<House> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("agent_id", id);
        int countByAgentId = houseMapper.selectCount(queryWrapper2);
        log.debug("根据经纪人ID统计匹配的house数量，结果：{}", countByAgentId);
        if (countByAgentId > 0) {
            String message = "删除经纪人失败，该经纪人仍有管理的house！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }



        int i = agentMapper.deleteById(id);
        if (i != 1) {
            String message = "删除失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.debug("删除成功！");
    }

    @Override
    public void updateById(Long id,AgentUpdateInfoParam agentUpdateInfoParam) {
        log.debug("开始处理【修改经纪人】的业务，ID：{}, 新数据：{}", id, agentUpdateInfoParam);
        // 检查经纪人是否存在，如果不存在，则抛出异常
        QueryWrapper<Agent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = agentMapper.selectCount(queryWrapper);
        log.debug("根据经纪人ID统计匹配的经纪人数量，结果：{}", countById);
        if (countById == 0) {
            String message = "修改经纪人信息失败，管理员数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        //查看修改的phoneNumber是否已经被其他经纪人占用
        log.debug("查看修改的phoneNumber是否已经被其他经纪人占用：");
        QueryWrapper<Agent> AdminQueryWrapper2 = new QueryWrapper<>();
        AdminQueryWrapper2.eq("phone_number", agentUpdateInfoParam.getPhoneNumber())
                .ne("id", id);
        int num = agentMapper.selectCount(AdminQueryWrapper2);
        log.debug("查询结果：{}", num);

        if (num > 0) {
            String message = "经纪人表中有相同电话号的数据，修改失败！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //查看修改的idCard是否已经被其他经纪人占用
        log.debug("查看修改的idCard是否已经被其他经纪人占用：");
        QueryWrapper<Agent> AdminQueryWrapper3 = new QueryWrapper<>();
        AdminQueryWrapper3.eq("id_card", agentUpdateInfoParam.getIdCard())
                .ne("id", id);
        num = agentMapper.selectCount(AdminQueryWrapper3);
        log.debug("查询结果：{}", num);

        if (num > 0) {
            String message = "经纪人表中有相同身份证号的数据，修改失败！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 执行修改
        log.debug("检查通过，开始修改！");
        Agent agent = new Agent();
        BeanUtils.copyProperties(agentUpdateInfoParam, agent);
        agent.setId(id);
        agent.setGmtModified(LocalDateTime.now());
        int i = agentMapper.updateById(agent);
        if (i != 1) {
            String message = "更新失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("将新的经纪人数据更新到数据库，完成！");
    }

    @Override
    public void setEnable(Long id) {
        updateEnableById(id, 1);
    }

    @Override
    public void setDisable(Long id) {
        updateEnableById(id, 0);
    }

    private void updateEnableById(Long id, Integer enable) {
        log.debug("开始处理【{}经纪人】的业务，ID：{}，目标状态：{}", ENABLE_TEXT[enable], id, enable);
        // 检查数据是否存在
        AgentStandardVO queryResult = agentMapper.getStandardById(id);
        if (queryResult == null) {
            String message = ENABLE_TEXT[enable] + "经纪人失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查当前状态是否与参数表示的状态相同
        if (queryResult.getEnable().equals(enable)) {
            String message = ENABLE_TEXT[enable] + "经纪人失败，当前经纪人已经处于"
                    + ENABLE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT, message);
        }

        // 准备执行更新
        Agent agent = new Agent();
        agent.setId(id);
        agent.setEnable(enable);
        log.debug("即将修改数据，参数：{}", agent);
        int rows = agentMapper.updateById(agent);
        if (rows != 1) {
            String message = ENABLE_TEXT[enable] + "经纪人失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public AgentStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询经纪人】的业务，参数：{}", id);
        AgentStandardVO queryResult = agentMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "查询经纪人失败，数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public PageData<AgentListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public PageData<AgentListItemVO> list(Integer pageNum,Integer pageSize) {
        log.debug("开始处理【查询经纪人列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<AgentListItemVO> list = agentMapper.list();
        PageInfo<AgentListItemVO> pageInfo = new PageInfo<>(list);
        PageData<AgentListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }
}
